/******************************************************************************
	This file is a part of the Snapshot Bioinformatics Project

	Copyright (C) 2012-2013 Jarom Schow

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/

#include "MySqlEmbedded.h"

#include "qsql_mysqld.h"

#include "Core.h"

using namespace Bio;

QString	MySqlEmbedded::s_configFile;
bool	MySqlEmbedded::s_initialized = false;

/**
**/
QSqlDatabase MySqlEmbedded::addDatabase( const QString &configFile, const QString &dbName )
{
	if( !s_initialized ){
		s_configFile = configFile;
		if( !initMySQL() )
			return QSqlDatabase();
	}

	MYSQL	*mysql = mysql_init( NULL );

	mysql_options( mysql, MYSQL_READ_DEFAULT_GROUP, "embedded" );
	mysql_options( mysql, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL );

	if( dbName.isEmpty() ){
		mysql_real_connect( mysql, NULL, NULL, NULL, NULL, 0, NULL, 0 );
	}
	else {
		QByteArray	db = dbName.toLatin1();

		mysql_real_connect( mysql, NULL, NULL, NULL, db.data(), 0, NULL, 0 );
	}

	QMYSQLdDriver *drv = new QMYSQLdDriver( mysql );

	return  QSqlDatabase::addDatabase( drv, "connection1" ); // Add the database connector to MySQL
}
	
/**
**/
bool MySqlEmbedded::initMySQL()
{
	QByteArray	config = QByteArray( "--defaults-file=" ) + s_configFile.toLatin1();
	char		*serverOptions[] = { "mysql_test", config.data(), NULL };
	int			numElements = 2;
	char		*serverGroups[] = { "embedded", NULL };

	if( mysql_library_init( numElements, serverOptions, serverGroups ) != 0 ){
		Core::error( "Failed to initialize the embedded MySQL server." );
		return false;
	}

	s_initialized = true;

	return true;
}

/**
**/
void MySqlEmbedded::endMySQL()
{
	if( s_initialized ){
		mysql_library_end();
		s_initialized = false;
	}
}
